package org.xiaojinlong.playground;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader;

import java.util.Arrays;

/**
 * @author Jin Long
 *         2016/2/28
 */
public class Shellsort {
    public static void sort(int[] a) {
        int len = a.length;
        int h = 1;
        while (h < (len / 3)) {
            h = 3 * h + 1;
        }

        while (h >= 1) {
            for (int i = h; i < len; i++) {
                for (int j = i; j >= h && less(a[j], a[j-h]); j = j - h) {
                    exch(a, j, j-h);
                }
            }

            h = h / 3;
        }
    }

    private static boolean less(int a, int b) {
        return ((a - b) < 0);
    }

    private static void exch(int[] arr, int a, int b) {
        int tmp = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp;
    }

    public static void main(String[] args) {
        int[] a = { 3, 8, 2, 9, 10, };
        sort(a);
        System.out.println(Arrays.toString(a));
    }
}
